package com.ztewatch.wearcontacts.view;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.provider.ContactsContract.Groups;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.ztewatch.wearcontacts.R;
import com.ztewatch.wearcontacts.loader.GroupListLoaderUtil;
import com.ztewatch.wearcontacts.loader.GroupMetaDataLoader;
import com.ztewatch.wearcontacts.utils.ContactPhotoUtils;

public class GroupListCursorAdapter extends CursorAdapter {
	Context mContext = null;
	LayoutInflater mInflater;

	public GroupListCursorAdapter(Context context, Cursor c) {
		super(context, c);
		mContext = context;
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		return mInflater.inflate(R.layout.grid_item, parent, false);
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		final TextView name_tv = (TextView) view.findViewById(R.id.item_text);
		final ImageView photo = (ImageView) view.findViewById(R.id.item_image);
		// photo.setImageResource(R.drawable.zte_contact_picture_holo_light);
		String name = cursor.getString(GroupMetaDataLoader.TITLE);
		name_tv.setText(name);
		bindPhoto(photo, cursor);
		int is_read_group_flag_index = cursor
				.getColumnIndex(Groups.GROUP_IS_READ_ONLY);
		if (is_read_group_flag_index != -1) {
			int read_group_flag = cursor.getInt(is_read_group_flag_index);
			if (read_group_flag == 1) {
				name_tv.setEnabled(false);
				photo.setEnabled(false);
				view.setTag(ContactCursorAdapter.IS_CLICK_FLAG, false);
			} else {
				name_tv.setEnabled(true);
				photo.setEnabled(true);
				view.setTag(ContactCursorAdapter.IS_CLICK_FLAG, true);
			}
		}
	}

	private void bindPhoto(ImageView photo, Cursor cursor) {
		int photo_index = cursor
				.getColumnIndex(GroupListLoaderUtil.GROUP_PHOTO_DATA);
		if (photo_index != -1) {
			byte[] photoarr = cursor.getBlob(photo_index);
			if (photoarr != null) {
				Bitmap bitmap = ContactPhotoUtils.Bytes2Bimap(photoarr);
				photo.setImageBitmap(bitmap);
			} else {
				photo.setImageResource(R.drawable.ic_friends);
			}
		} else {
			photo.setImageResource(R.drawable.ic_friends);
		}
	}
}
